package com.tansun.ruledata.controller;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.drools.core.util.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.tansun.rule.config.AppConfiguration;
import com.tansun.rule.utils.IOUtils;
import com.tansun.rule.utils.JsonMessage;
import com.tansun.rule.utils.MClass;
import com.tansun.rule.utils.RuleMapAndJsonUtils;
import com.tansun.ruledata.data.service.RuleResourceLoadService;
import com.tansun.ruledata.entity.RuleExcuterParam;
import com.tansun.ruledata.service.RuleDataBusinessService;

@Controller
@RequestMapping(value = "/ruleService")
public class RuleServiceController {
	private Logger log = LoggerFactory.getLogger(this.getClass());
	@Autowired
	private RuleDataBusinessService ruleDataBusinessService;
	@Autowired
	private RuleResourceLoadService ruleResourceLoadService;

	
	/**
	 * 规则执行接口
	 * 
	 * @param projectCode
	 * @param enterPoint
	 * @param businessInput
	 * @return
	 * @throws Exception 
	 */
	@RequestMapping(value = "/ruleEngineService", method = RequestMethod.POST)
	public @ResponseBody String ruleEngineService(HttpServletRequest request, HttpServletResponse response,
			ModelMap map) throws Exception {
//		long start = System.currentTimeMillis();
		String projectCode = request.getParameter("projectCode");
		String enterPoint = request.getParameter("enterPoint");
		String businessInput = request.getParameter("businessInput");
		String type = request.getParameter("type");
		if (StringUtils.isEmpty(type)) {
			type = "json";
		}
		String result = ruleDataBusinessService.ruleEngineService(projectCode, enterPoint, type, businessInput);
//		log.info("CertificationBean-调用服务时间：" + (System.currentTimeMillis() - start));
		return result;
	}
	/**
	 * 规则执行接口-卡中心
	 * 
	 * @param request
	 * @param response
	 * @param map
	 * @return
	 */
	@RequestMapping(value = "/ruleEngineService_vo", method = RequestMethod.POST)
	public @ResponseBody String ruleEngineService_vo(@RequestBody RuleExcuterParam param) {
//		String result = ruleDataBusinessService.ruleEngineService(param.getProjectCode(), param.getEnterPoint(), "json", param.getBusinessInput());
		Map<String,Object> businessInputMap = (Map<String,Object>) JSON.parse(param.getBusinessInput().toString());
		Map<String, Object> resultMap = ruleDataBusinessService.ruleEngineService(param.getProjectCode(), param.getEnterPoint(), businessInputMap);
//		 SerializeConfig fconfig = SerializeConfig.getGlobalInstance();
//		 fconfig.put(Double.class, new DoubleSerializer("0.0#########"));
		return JSON.toJSONString(resultMap);
	}

	
	/**
	 * 针对交行总行的，即Rule_Exe前缀的表
	 * @param param
	 * @return
	 */
	@RequestMapping(value = "/ruleEngineService_ruleExe", method = RequestMethod.POST)
	public @ResponseBody String ruleEngineService_ruleExe(@RequestBody RuleExcuterParam param) {
//		String result = ruleDataBusinessService.ruleEngineService(param.getProjectCode(), param.getEnterPoint(), "json", param.getBusinessInput());
		Map<String,Object> businessInputMap = (Map<String,Object>) JSON.parse(param.getBusinessInput().toString());
		Map<String, Object> resultMap = ruleDataBusinessService.ruleEngineService_ruleExe(param.getProjectCode(), param.getEnterPoint(), businessInputMap);
		return JSON.toJSONString(resultMap);
	}
	/**
	 * 获取规则流使用的参数
	 * 
	 * @param projectCode
	 * @param enterPoint
	 * @return
	 */
	@RequestMapping("/ruleFlowParamInfo")
	public @ResponseBody JsonMessage ruleFlowParamInfo(String projectCode, String enterPoint) {
		JsonMessage ret = new JsonMessage();
		try {
			String result = ruleDataBusinessService.ruleFlowParamInfo(projectCode, enterPoint);
			ret.setData(result);
		} catch (Exception e) {
			// TODO: handle exception
			log.error(e.getMessage(), e);
			ret.setResult(false);
			ret.setMessage(IOUtils.getStackTraceMsg(e));
		}
		return ret;
	}

	@RequestMapping(value = "/initRuleParamStr", method = RequestMethod.POST)
	public @ResponseBody JsonMessage initRuleParamStr(HttpServletRequest request) {
		JsonMessage ret = new JsonMessage();
		try {
			String projectCode = request.getParameter("projectCode");
			String enterPoint = request.getParameter("enterPoint");
			String businessInput = request.getParameter("businessInput");
			Map<String,Object> requestMap = JSON.parseObject(businessInput, Map.class);
			Map<String,Object> result = ruleDataBusinessService.initRuleParamMap(projectCode, enterPoint, requestMap);
			ret.setData(JSON.toJSONString(result));
		} catch (Exception e) {
			// TODO: handle exception
			log.error(e.getMessage(), e);
			ret.setMessage(e.getMessage());
			ret.setResult(false);
		}
		return ret;
	}

	@RequestMapping({ "/ruleProjectParamInfo" })
	public @ResponseBody String ruleProjectParamInfo() {
		try {
			return this.ruleDataBusinessService.ruleProjectParamInfo();
		} catch (Exception e) {
			this.log.error(e.getMessage(), e);
		}
		return null;
	}
	/**
	 * 规则执行日志查询接口
	 * @param request
	 * @param map
	 * @return
	 * @throws Exception
	 */
	@RequestMapping({ "/ruleExecutionLog" })
	public @ResponseBody String ruleExecutionLog(HttpServletRequest request) {
		String projectCode = request.getParameter("projectCode");
		try {
			return this.ruleDataBusinessService.ruleExecutionLogList(projectCode);
		} catch (Exception e) {
			this.log.error(e.getMessage(), e);
		}
		return null;
	}
	/**
	 * 规则执行日志项目详情查询接口
	 * @param request
	 * @param map
	 * @return
	 * @throws Exception
	 */
	@RequestMapping({ "/ruleExecutionLogDetails" })
	public @ResponseBody String ruleExecutionLogDetails(HttpServletRequest request) {
		String projectCode = request.getParameter("projectCode");
		String ruleFlowId = request.getParameter("ruleFlowId");
		try {
			return this.ruleDataBusinessService.ruleExecutionLogDetails(projectCode, ruleFlowId);
		} catch (Exception e) {
			this.log.error(e.getMessage(), e);
		}
		return null;
	}

	/**
	 * 联机部署方式调用
	 * @param param
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/ruleEngineServiceBcm_vo", method = RequestMethod.POST)
	public @ResponseBody RuleExcuterParam ruleEngineServiceBcm_vo(@RequestBody RuleExcuterParam param) throws Exception {
		try {
			Map<String,Object> businessInputMap = JSONObject.toJavaObject(param.getBusinessInput(), Map.class);
			Map<String, Object> requestMap= initRequest(param.getProjectCode(), businessInputMap);
//			Map<String, Object> requestMap = ruleDataBusinessService.initRuleParamMap(param.getProjectCode(), param.getEnterPoint(), businessInputMap);
			Map<String, Object> resultMap = ruleDataBusinessService.ruleEngineService(param.getProjectCode(), param.getEnterPoint(), requestMap);
			RuleMapAndJsonUtils.mapConverJson_1(resultMap, businessInputMap);
//			SerializeConfig fconfig = SerializeConfig.getGlobalInstance();
//			fconfig.put(Double.class, new DoubleSerializer("0.0#######"));
			param.setBusinessInput((JSONObject) JSONObject.parse(JSON.toJSONString(businessInputMap)));
			businessInputMap=null;
			resultMap = null;
		}catch(Exception e) {
			e.printStackTrace();
			param.setErrMsg(e.getMessage());
		}
		return param;
	}



	private Map<String, Object> initRequest(String projectCode,Map<String,Object> businessInputMap) throws Exception{
		Map<String, MClass> metaMap = AppConfiguration.RuleProjMetaMap.get(projectCode);
		if (metaMap == null || metaMap.isEmpty()){
			this.ruleResourceLoadService.loadProjectDataMapping(projectCode);
			metaMap = AppConfiguration.RuleProjMetaMap.get(projectCode);
		}
		Map<String, Object> insertMap = RuleMapAndJsonUtils.jsonCoverMap(businessInputMap, metaMap,true);
		return insertMap;
	}
	
}
